package com.soft.mainsite.module.web.cms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.soft.mainsite.common.constant.CmsConst;
import com.soft.mainsite.common.exception.CmsException;
import com.soft.mainsite.common.utils.HtmlKit;
import com.soft.mainsite.common.utils.JsonUtil;
import com.soft.mainsite.common.utils.PinyinUtil;
import com.soft.mainsite.module.category.dao.TCmsCategoryDao;
import com.soft.mainsite.module.staticstrategy.staticservice.StaticHtmlService;
import com.soft.mainsite.module.web.cms.service.CategoryService;
import com.soft.mainsite.mybatis.mapper.TCmsCategoryMapper;
import com.soft.mainsite.mybatis.mapper.TCmsContentMapper;
import com.soft.mainsite.mybatis.model.TCmsCategory;
import com.soft.mainsite.mybatis.model.TCmsContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Description:栏目分类
 *
 * @author Jin
 * @create 2017-04-18
 */
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private TCmsCategoryMapper categoryMapper;
    @Resource
    private TCmsContentMapper contentMapper;
    @Resource
    private TCmsCategoryDao categoryDao;
    @Autowired
    private StaticHtmlService staticHtmlService;

    @Override
    public String save(TCmsCategory pojo) {
        // 将栏目名称转换为拼音设置别名
        if (StrUtil.isBlank(pojo.getAlias())) {
            pojo.setAlias(PinyinUtil.convertLower(HtmlKit.getText(pojo.getCategoryName())).replace(" ", "-").trim());
        } else {
            pojo.setAlias(PinyinUtil.convertLower(HtmlKit.getText(pojo.getAlias())).replace(" ", "-").trim());
        }
        // 判断是否设置当前栏目为顶级节点
        if (pojo.getParentId() != 0L) {
            TCmsCategory parentCategory = categoryMapper.selectByPrimaryKey(pojo.getParentId());
            parentCategory.setHasChild(true);
            categoryMapper.updateByPrimaryKeySelective(parentCategory);
            // 判断当前栏目是否需要继承父类模板
            if (StrUtil.isBlank(pojo.getContentTpl())) {
                pojo.setContentTpl(StrUtil.isBlank(parentCategory.getContentTpl()) ? CmsConst.CONTENT_TPL : parentCategory.getContentTpl());
            }
            if (StrUtil.isBlank(pojo.getIndexTpl())) {
                pojo.setIndexTpl(StrUtil.isBlank(parentCategory.getIndexTpl()) ? CmsConst.CATEGORY_INDEX_TPL : parentCategory.getIndexTpl());
            }
            if (StrUtil.isBlank(pojo.getListTpl())) {
                pojo.setListTpl(StrUtil.isBlank(parentCategory.getListTpl()) ? CmsConst.CATEGORY_LIST_TPL : parentCategory.getListTpl());
            }
        } else {
            pojo.setContentTpl(StrUtil.isBlank(pojo.getContentTpl()) ? CmsConst.CONTENT_TPL : pojo.getContentTpl());
            pojo.setIndexTpl(StrUtil.isBlank(pojo.getIndexTpl()) ? CmsConst.CATEGORY_INDEX_TPL : pojo.getIndexTpl());
            pojo.setListTpl(StrUtil.isBlank(pojo.getListTpl()) ? CmsConst.CATEGORY_LIST_TPL : pojo.getListTpl());
        }
        if (categoryMapper.insert(pojo) > 0) {
            return JsonUtil.toSuccess("分类添加成功！", "category-tab", true);
        }
        return JsonUtil.toError("分类添加失败！");
    }


    @Transactional(transactionManager = "masterTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public String update(TCmsCategory pojo) {
        // 将栏目名称转换为拼音设置别名
        if (categoryMapper.selectByPrimaryKey(pojo.getCategoryId()).getParentId() == 0 && pojo.getParentId() != 0L) {
            // 父类交换
            TCmsCategory parentCategory = categoryMapper.selectByPrimaryKey(pojo.getParentId());
            parentCategory.setParentId(0L);
            parentCategory.setHasChild(true);
            pojo.setParentId(pojo.getParentId());
            categoryMapper.updateByPrimaryKey(parentCategory);
            // 判断当前栏目是否需要继承父类模板
            if (StrUtil.isBlank(pojo.getContentTpl())) {
                pojo.setContentTpl(StrUtil.isBlank(parentCategory.getContentTpl()) ? CmsConst.CONTENT_TPL : parentCategory.getContentTpl());
            }
            if (StrUtil.isBlank(pojo.getIndexTpl())) {
                pojo.setIndexTpl(StrUtil.isBlank(parentCategory.getIndexTpl()) ? CmsConst.INDEX_TPL : parentCategory.getIndexTpl());
            }
            if (StrUtil.isBlank(pojo.getListTpl())) {
                pojo.setListTpl(StrUtil.isBlank(parentCategory.getListTpl()) ? CmsConst.CATEGORY_LIST_TPL : parentCategory.getListTpl());
            }
        } else {
            pojo.setContentTpl(StrUtil.isBlank(pojo.getContentTpl()) ? CmsConst.CONTENT_TPL : pojo.getContentTpl());
            pojo.setIndexTpl(StrUtil.isBlank(pojo.getIndexTpl()) ? CmsConst.INDEX_TPL : pojo.getIndexTpl());
            pojo.setListTpl(StrUtil.isBlank(pojo.getListTpl()) ? CmsConst.CATEGORY_LIST_TPL : pojo.getListTpl());
        }
        if (categoryMapper.updateByPrimaryKeySelective(pojo) > 0) {
            // 更新完成后  根据全站检索选项  删除、增加、或者更新ES内容
            Long categoryId = pojo.getCategoryId();


            // 静态化栏目首图
            try {
                staticHtmlService.common(CmsConst.MAIN_SITE_ID, "common/mediaCenter/hotspot_information_fragment", CmsConst.TPL_TYPE_MOBILE);
            } catch (Exception e) {
                log.error("静态化栏目首图失败", e);
            }

            /*staticHtmlService.category(pojo.getSiteId(), pojo.getCategoryId(), CmsConst.TPL_TYPE_MOBILE);*/
            return JsonUtil.toSuccess("分类更新成功！", "category-tab", false);
        }
        return JsonUtil.toError("分类更新失败！");
    }

    @Transactional(transactionManager = "masterTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public String delete(Long[] ids) {
        if (ids != null && ids.length > 0) {
            for (Long id : ids) {
                // 先遍历获取当前子栏目
                TCmsCategory category = new TCmsCategory();
                category.setParentId(id);
                List<TCmsCategory> categories = categoryMapper.select(category);
                if (categories != null && categories.size() > 0) {
                    for (TCmsCategory c : categories) {
                        TCmsContent content = new TCmsContent();
                        content.setCategoryId(c.getCategoryId());
                        if (contentMapper.selectCount(content) > 0) {
                            throw new CmsException("当前栏目[" + id + "]下有多条内容，不允许删除");
                        }
                        categoryMapper.deleteByPrimaryKey(c.getCategoryId());
                    }
                    categoryMapper.deleteByPrimaryKey(id);
                } else {
                    TCmsContent content = new TCmsContent();
                    content.setCategoryId(id);
                    if (contentMapper.selectCount(content) > 0) {
                        throw new CmsException("当前栏目[" + id + "]下有多条内容，不允许删除");
                    }
                    Long parentId = findById(id).getParentId();
                    categoryMapper.deleteByPrimaryKey(id);
                    hasChildUpdate(parentId);
                }
            }
        }
        return JsonUtil.toSuccess("删除成功！", "category-tab", true);
    }

    private void hasChildUpdate(Long id) {
        if (id != null && id != 0L) {
            TCmsCategory category = findById(id);
            List<TCmsCategory> categories = findCategoryListByPid(id);
            if (CollectionUtils.isNotEmpty(categories) && categories.size() > 0) {
                category.setHasChild(Boolean.TRUE);
                update(category);
            } else {
                category.setHasChild(Boolean.FALSE);
                update(category);
            }
        }
    }

    @Override
    public PageInfo<TCmsCategory> page(Integer pageNumber, Integer pageSize, TCmsCategory pojo) {
        PageHelper.startPage(pageNumber, pageSize);
        return new PageInfo(categoryMapper.select(pojo));
    }

    @Override
    public PageInfo<TCmsCategory> page(Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        PageInfo<TCmsCategory> pageInfo = new PageInfo();
        pageInfo.setList(categoryMapper.selectAll());
        return pageInfo;
    }


    @Override
    public TCmsCategory findById(Long id) {
        TCmsCategory category = categoryMapper.selectByPrimaryKey(id);
        if (category != null && StrUtil.isNotBlank(category.getCategoryImg())) {
            String categoryImg = StrUtil.removeSuffix(category.getCategoryImg(), ",");
            category.setCategoryImg(categoryImg);
        }
        return category;
    }

    @Override
    public List<TCmsCategory> findList(TCmsCategory pojo) {
        return categoryMapper.select(pojo);
    }

    @Override
    public List<TCmsCategory> findAll() {
        return categoryMapper.selectAll();
    }


    @Override
    public List<TCmsCategory> findCategoryListByPid(Long pid) {
        TCmsCategory category = new TCmsCategory();
        category.setParentId(pid);
        return categoryMapper.select(category);
    }

    @Override
    public List<TCmsCategory> findCategoryListBySiteId(Integer siteId) {
        TCmsCategory category = new TCmsCategory();
        category.setSiteId(siteId);
        return categoryMapper.select(category);
    }

    @Override
    public List<TCmsCategory> findInitCategoryList(Integer siteId, Integer isCommon) {
        return categoryMapper.listAllBySiteId(siteId, isCommon);
    }

    @Override
    public List<TCmsCategory> findCategoryListByPid(Long pid, Integer siteId) {
        return categoryDao.findCategoryListByPid(pid, siteId);
    }

    @Override
    public List<TCmsCategory> findCategoryListByPidAndIsNav(Long pid, Integer siteId, Boolean isNav) {
        TCmsCategory category = new TCmsCategory();
        category.setParentId(pid);
        category.setSiteId(siteId);
        if (isNav) {
            category.setIsNav(isNav);
        }
        return categoryMapper.select(category);
    }

    @Override
    public TCmsCategory findByAlias(String alias) {
        TCmsCategory category = new TCmsCategory();
        category.setAlias(alias);
        return categoryMapper.selectOne(category);
    }


    @Override
    public Integer findPageSize(Long categoryId) {
        return this.categoryMapper.selectByPrimaryKey(categoryId).getPageSize();
    }


    @Override
    public TCmsCategory findfindByAliasAndSiteId(String alias, Integer siteId) {
        TCmsCategory category = new TCmsCategory();
        category.setAlias(alias);
        category.setSiteId(siteId);
        return categoryMapper.selectOne(category);
    }

    @Override
    public Integer allCount() {
        return this.categoryMapper.selectCount(new TCmsCategory());
    }

    @Override
    public Integer[] getAllowSearchCategoryIds() {
        return categoryMapper.selectAllowSearchCategoryIds();
    }

    @Override
    public List<TCmsCategory> findAllCategoryTplBySiteId(Integer siteId) {
        return categoryMapper.getAllCategoryTplBySiteId(siteId);
    }
}
